import React, { useEffect, useState } from 'react';
import { Modal, Spin, message } from 'antd';
import TRNotification from '#/utils/notification.js';
import { HttpCode } from '#/utils/contacts.js';
import { TRDefault } from '@/components/index.js';
import { postQueryDoubleNodeBlockList } from '../../service';
import type { IEchartParamsType, IDateChartsDataType } from '../../type';
import { IPointerType } from '../../type';
import { pointerOptions } from '../../dictionary';
import { Charts, Pointer } from '../index';
import { TIME_ENUM } from '../../tool';
import planIcon from '@/assets/img/plan_icon.png';
import planIconDark from '@/assets/img/plan_icon_dark.png';
import planIconGre from '@/assets/img/plan_icon_gre.png';
import styles from './index.less';
// @ts-ignore
import emitter from '#/utils/events';

interface IProps {
  /**
   * params请求参数
   */
  params?: IEchartParamsType;
  /**
   * x轴节点名称
   */
  nodeXName?: string;
  /**
   * x轴节点名称
   */
  nodeYName?: string;
  onPress: (data: Record<string, any>) => void;
}

const EchartsModalComponent = (props: IProps) => {
  const { onPress, params, nodeXName, nodeYName } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(true);
  const [isError, setIsError] = useState<boolean>(false);
  const [pointNum, setPointNum] = useState<IPointerType>(IPointerType.NINETY_SIX_POINT); // 时点
  const [dateChartsData, setDateChartsData] = useState<IDateChartsDataType>();
  const [xAxisData, setXAxisData] = useState<string[]>([]);

  const [theme, setTheme] = useState(localStorage.getItem('saas-theme') || 'dark');

  const fetchData = async (_params: IEchartParamsType) => {
    setLoading(true);
    const res = await postQueryDoubleNodeBlockList(_params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setIsError(false);
      setDateChartsData(res?.data || {});
    } else {
      setIsError(true);
      message.error(res?.message || '系统异常');
    }
    setLoading(false);
  };

  // 24点和96点切换
  const onChangePointNum = (e: IPointerType) => {
    const _params = {
      ...params,
      mode: e,
    };
    fetchData(_params);
    const _xAxisData = TIME_ENUM(e);
    setXAxisData(_xAxisData);
    setPointNum(e);
  };

  // 取消按钮
  const _onCancel = () => {
    setVisible(false);
    onPress({ index: 0 });
  };

  useEffect(() => {
    if (params) {
      fetchData(params);
      const _pointNum = params?.mode || IPointerType.NINETY_SIX_POINT;
      const _xAxisData = TIME_ENUM(_pointNum);
      setXAxisData(_xAxisData);
    }
  }, [params]);

  useEffect(() => {
    emitter.addListener('onGlobalThemeChange', (e) => {
      setTheme(e.key);
    });
    return () => {
      emitter.removeListener('onGlobalThemeChange', () => {});
    };
  }, []);

  const title =
    nodeXName && nodeYName && params?.blockName
      ? `${nodeXName}-${nodeYName}-${params?.blockName}通道阻塞价格`
      : '通道阻塞价格';

  return (
    <Modal
      className={styles.modal}
      centered
      width={800}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <div className={styles.left}>
            <img
              src={theme === 'dark' ? planIconDark : theme === 'gre' ? planIconGre : planIcon}
              className={styles.titleLogo}
            />
            <span className={styles.title}>{title}</span>
          </div>
          <Pointer value={pointNum} options={pointerOptions} onChange={onChangePointNum} />
        </div>
      }
      onCancel={_onCancel}
      footer={null}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin />
        ) : isError ? (
          <TRDefault type={'error'} message={'系统异常'} />
        ) : dateChartsData ? (
          <div className={styles.echarts}>
            <div className={styles.echartsHeader}>
              <div className={styles.echartsHeaderLeft}>节点价格</div>
              <div className={styles.echartsHeaderRight}>阻塞价格</div>
            </div>
            <Charts
              data={dateChartsData}
              xAxisData={xAxisData}
              nodeXName={nodeXName}
              nodeYName={nodeYName}
              date={params?.date}
            />
          </div>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </Modal>
  );
};

class EchartsModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <EchartsModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new EchartsModal();
